/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
// import {
// 	baseUrl
// } from '@/config/env';
import config from '../../public/config.js'
import {
	serialize
} from '@/util/util'
import {
	getToken
} from '@/util/auth'
import {
	Message
} from 'element-ui'
//import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
axios.defaults.timeout = 60000;
//返回其他状态吗
axios.defaults.validateStatus = function(status) {
	return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
	showSpinner: false
});
//HTTPrequest拦截
axios.interceptors.request.use(cfg => {
	NProgress.start() // start progress bar
	const meta = (cfg.meta || {});
	if (cfg.url.substr(0, 5) == "/api/") {
		cfg.url = config.burl + cfg.url
	} else if (cfg.url.substr(0, 6) == "2/api/") {
		cfg.url = config.burl2 + cfg.url.substr(1, cfg.url.length - 1)
	}
	const isToken = meta.isToken === false;
	if (getToken() && !isToken) {
		cfg.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
	}
	//headers中配置serialize为true开启序列化
	if (cfg.method === 'post' && meta.isSerialize === true) {
		cfg.data = serialize(cfg.data);
	}
	return cfg
}, error => {
	return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
	NProgress.done();
	const status = Number(res.data.code) || 200;
	//const statusWhiteList = website.statusWhiteList || [];
	const message = res.data.msg || '未知错误';
	//如果在白名单里则自行catch逻辑处理
	//if (statusWhiteList.includes(status)) return Promise.reject(res);
	//如果是401则跳转到登录页面
	if (status === 401) store.dispatch('FedLogOut').then(() => router.push({
		path: '/login'
	}));
	// 如果请求为非200否者默认统一处理
	if (status !== 200) {
		Message({
			showClose: true,
			duration: 10000,
			message: message,
			type: 'error'
		})
		//return Promise.reject(new Error(message))
	} else {
		if (res.config.method == "post" && res.config.url.indexOf(
				"api/files/upload") === -1) {
			Message({
				type: "success",
				message: "操作成功!"
			});
		}
	}
	return res;
}, error => {
	NProgress.done();
	Message({
		message: error,
		type: 'error'
	})
	return Promise.reject(new Error(error));
})
export default axios;
